package com.zzyk.main.service.impl;

import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.mapper.SysRoleDao;
import com.zzyk.main.model.pojo.SysRole;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.pojo.UserRole;
import com.zzyk.main.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SysRoleServiceImpl extends BaseController implements ISysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Override
    public SysRole getRole(int roleId) {
        return sysRoleDao.getRoleById(roleId);
    }

    @Override
    public SysRole getRole(String roleName) {
        return sysRoleDao.getRoleByName(roleName);
    }

    @Override
    public List<SysRole> getRoleList(SysRole sysRole) {
        if (sysRole != null && sysRole.getId() != null) {
            return sysRoleDao.getRoleListWithPermission(sysRole.getId());
        } else {
            return sysRoleDao.getRoleList(sysRole);
        }
    }

    @Override
    public int addRole(SysRole sysRole) {
        return sysRoleDao.addRole(sysRole);
    }

    @Override
    public int updateRole(SysRole sysRole) throws UserException {
        SysUser authUser = currentUser();
        sysRole.setUpdateBy(authUser.getId());
        sysRole.setUpdateTime(new Date());
        return sysRoleDao.updateRole(sysRole);
    }

    @Override
    public int deleteRole(int roleId) {
        return sysRoleDao.deleteRole(roleId);
    }

    @Override
    public int addUserRole(UserRole userRole) {
        return sysRoleDao.addUserRole(userRole);
    }

    @Override
    public int deleteUserRole(UserRole userRole) {
        return sysRoleDao.deleteUserRole(userRole);
    }

    @Override
    public int changeUserRole(Integer userId, Integer roleId) {
        Set<SysRole> sysRoles = sysRoleDao.getRoleSetByUserId(userId);
        for (SysRole sysRole : sysRoles) {
            sysRoleDao.deleteUserRole(new UserRole(userId, sysRole.getId()));
        }
        return sysRoleDao.addUserRole(new UserRole(userId, roleId));
    }

    @Override
    public Set<SysRole> getRoleSetByUserId(int userId, boolean permission) {
        if (permission) {
            return sysRoleDao.getRoleSetByUserIdWithPermission(userId);
        } else {
            return sysRoleDao.getRoleSetByUserId(userId);
        }
    }

    @Override
    public List<SysRole> getOrdinaryRole() {
        return sysRoleDao.getOrdinaryRole();
    }
}
